<!--  -->
<template>
  <div>
      <Card>
        <p slot="title">
            <Icon class="rotate-title-icon" style="color:#2F65EB" type="minus"></Icon>
            子管理员
            <Poptip placement="right-start" trigger="hover"  content="可以登录管理后台、查看后台数据、进行管理操作的人员。">
                <Icon  style="color:#2d8cf0;cursor:pointer" type="information-circled"></Icon>
            </Poptip>
        </p>
        <Button  v-if="btnp.zglyuan_xz" slot="extra" size="small" class="zh-hollow" type="primary" @click="handleAdd" icon="plus-round">新增</Button>
        <Table :loading="loading" border :columns="columns" :data="data"></Table>
        <Page :current.sync='pageNumber' :total="total" show-total show-sizer @on-change="pageChange" @on-page-size-change="pageSizeChange"></Page>
     </Card>
    <Modal :loading="saveLoad" v-model="modal_mg" :title="modalTitle" @on-ok='validate'  ok-text="保存" cancel-text="放弃操作" :mask-closable="false" :class="mobileIsTrue?'':'no_footer_modal'">
      <Form :model="mgInfo" :label-width="80" style="padding:15px 30px;">
        <template v-if="modalTitle=='修改子管理员权限'">
          <FormItem label="手机号">
            <Input v-model="mgInfo.mobile" readonly></Input>
          </FormItem>
          <FormItem label="姓名">
            <Input readonly v-model="mgInfo.name" ></Input>
          </FormItem>
          <FormItem label="所属机构">
            <Input readonly v-model="mgInfo.inst_name"  ></Input>
          </FormItem>
          <FormItem label="权限范围">
            <RadioGroup v-model="mgInfo.authority">
              <Radio label="0"><span>所属机构本级及下级</span></Radio>
              <Radio label="1"><span>仅限所属机构本级</span></Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="管理权限">
            <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
                <Checkbox
                    :indeterminate="indeterminate"
                    :value="checkAll"
                    @click.prevent.native="handleCheckAll">以下全部</Checkbox>
            </div>
            <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
                <Checkbox label="8148d7c810964be998d68ddb10e615f5"><span>行政权限（包括组织机构、人员管理、系统管理等）</span> </Checkbox>
                <Checkbox label="94fe763a7072479cb5714b49f774c67c"><span>运维权限（包括设备维修、场地巡检、设备管理等）</span> </Checkbox>
                <Checkbox label="3d171d56f0a1410c8b41a61dd45755c0"><span>办公用品（包括办公用品采购的全流程管理）</span> </Checkbox>
                <Checkbox label="7c3d83aff33c4bbeb36ab44cbb084ffe"><span>凭证权限（包括凭证请领的全流程管理）</span> </Checkbox>
            </CheckboxGroup>
          </FormItem>
        </template>
        <template v-else>
          <FormItem label="手机号">
            <Input  @on-change='mobileChange' v-model="mgInfo.mobile" :maxlength="11" placeholder="可填写已注册点点维APP的手机号"></Input>
          </FormItem>
          <template v-if="mobileIsTrue">
            <template v-if="isRegister">
              <FormItem label="姓名">
                <Input readonly v-model="mgInfo.name" ></Input>
              </FormItem>
              <FormItem label="所属机构">
                <Input readonly v-model="mgInfo.inst_name" ></Input>
              </FormItem>
            </template>
            <template v-else>
              <FormItem label="姓名*">
                <Input  v-model="mgInfo.name" :maxlength="5" ></Input>
              </FormItem>
              <FormItem label="所在地*">
                <Cascader change-on-select v-model="mgInfo.location" placeholder="请选择省市区" :data="areasData" ></Cascader>
              </FormItem>
              <FormItem label="所在机构*">
				  <Input  @on-focus="f_tree=true;" v-model="mgInfo.inst_name" placeholder="请选择机构" readonly></Input>
                <!-- <Select  v-model="mgInfo.instUuid" filterable @on-change="instChange">
                    <Option  v-for="item in instList" :value="item.uuid" :key="item.uuid">{{ item.name }}</Option>
                </Select> -->
              </FormItem>
              <FormItem label="部门" v-if="mgInfo.instUuid.length>0">
                <Select   v-model="mgInfo.deptUuid" filterable>
                    <Option  v-for="item in partList" :value="item.uuid" :key="item.uuid">{{ item.name }}</Option>
                </Select>
              </FormItem>
              <FormItem label="设置密码*">
                <Input v-model="mgInfo.password" type="password" placeholder="8-20位，同时包含字母和数字"></Input>
              </FormItem>
              <FormItem label="确认密码*">
                <Input v-model="mgInfo.repassword" type="password" placeholder="再次输入密码"></Input>
              </FormItem>
            </template>
            <FormItem label="权限范围">
              <RadioGroup v-model="mgInfo.authority">
                <Radio label="0"><span>所属机构本级及下级</span></Radio>
                <Radio label="1"><span>仅限所属机构本级</span></Radio>
              </RadioGroup>
            </FormItem>
            <FormItem label="管理权限">
              <div style="border-bottom: 1px solid #e9e9e9;padding-bottom:6px;margin-bottom:6px;">
                  <Checkbox
                      :indeterminate="indeterminate"
                      :value="checkAll"
                      @click.prevent.native="handleCheckAll">以下全部</Checkbox>
              </div>
              <CheckboxGroup v-model="checkAllGroup" @on-change="checkAllGroupChange">
                  <Checkbox label="8148d7c810964be998d68ddb10e615f5"><span>行政权限（包括组织机构、人员管理、系统管理等）</span> </Checkbox>
                  <Checkbox label="94fe763a7072479cb5714b49f774c67c"><span>运维权限（包括设备维修、场地巡检、设备管理等）</span> </Checkbox>
                  <Checkbox label="3d171d56f0a1410c8b41a61dd45755c0"><span>办公用品（包括办公用品采购的全流程管理）</span> </Checkbox>
                  <Checkbox label="7c3d83aff33c4bbeb36ab44cbb084ffe"><span>凭证权限（包括凭证请领的全流程管理）</span> </Checkbox>
              </CheckboxGroup>
            </FormItem>
          </template> 
        </template>
        
      </Form>
    </Modal>
	<Modal title="选择机构" v-model="f_tree" :loading="ft_load" @on-ok="confirmF" :mask-closable="false" >
			<div style="padding:15px 30px;">
				<Tree :data="f_tree_data"   @on-select-change="f_selectChange"></Tree>
			</div>
		</Modal>
  </div>
</template>

<script>
import util from '@/libs/util.js'
import {getBankOrg,getDeptList,getOrgTree} from '@/libs/get.js'
import {getSubAdminsTable,deleteSubadmins,mobilepd,saveSubAdmins} from '@/libs/system.js'
export default {
name:'',
  	data () {
    	return {
			ft_load:true,
			f_select_op:[],
			f_tree_data:[],
			f_tree:false,
			userUuid:'',
			user_type:'',
			areasData:this.$store.state.user.areaData,
			saveLoad:true,
			btnp:{},
			btn:{
				zglyuan_xz:false,
				zglyuan_xgqx:false,
				zglyuan_scgly:false
			},
			partList:[],
			instList:[],
			mobileIsTrue:false,
			isRegister:false,
			pageSize:10,
			pageNumber:1,
			indeterminate: true,
			checkAll: false,
			checkAllGroup: [],
			saveUuid:'',
			mgInfo:{
				mobile:'',
				name:'',
				inst_name:'',
				authority:'',
				roleManager:'',
				location:[],
				instUuid:'',
				deptUuid:'',
				password:'',
				repassword:''
			},
			modal_mg:false,
			modalTitle:'',
			loading:true,
			total:2,
			columns:[
				{
				key:'mobile',
				title:'手机号',
				align:'center',
				minWidth:120
				},
				{
				key:'name',
				title:'人员姓名',
				align:'center',
				minWidth:100
				},
				{
				key:'inst_name',
				title:'所属机构',
				align:'center',
				minWidth:120
				},
				{
				key:'authorityName',
				title:'权限范围',
				align:'center',
				minWidth:120
				},
				{
				key:'roleNames',
				title:'管理权限',
				minWidth:150
				},
				{
				key:'action',
				title:'操作',
				align:'center',
				minWidth:200,
				fixed:'right',
				render:(h,params)=>{
					return h('div',[
					h('Button',{
						props:{
						type:'text',
						size:'small'
						},
						style:{
						color:'#2D8CF0',
						display:this.btnp.zglyuan_xgqx?'inline-block':'none'
						},
						on:{
						click:()=>{
							this.gotoChangePower(params.row)
						}
						}
					},'修改权限'),
					h('Button',{
						props:{
						type:'text',
						size:'small'
						},
						style:{
						color:'#EA0000',
						display:this.btnp.zglyuan_scgly?'inline-block':'none'
						},
						on:{
						click:()=>{
							let config={
							title:'删除子管理员',
							content:'删除子管理员后，该人员不能再登录后台。手机APP仍可正常使用。',
							okText:'删除',
							cancelText:'放弃操作',
							onOk:()=>{
								this.delete(params.row.uuid)
							}
							}
							this.$Modal.confirm(config)
						}
						}
					},'删除管理员')
					])
				}
				}
			],
			data:[],
		};
  	},
  	methods:{
		async getInst(uuid){
			if(this.instList.length<=0){
				let res=await getBankOrg(uuid);
				let response=res.data;
				if(response.code===200){
					this.instList=response.data;
				}else{
					this.$Notice.error({
						desc:response.msg
					});
				}
			}
		},
		async getFormInstTree(value,p,c,d){
			this.mgInfo.instUuid='';
			this.mgInfo.inst_name='';
			this.f_select_op=[];
			if(value!==''){
				let res=await getOrgTree(value,p,c,d);
				let response=res.data;
				if(response.code===200){
					this.f_tree_data=util.tree([response.data]);
				}else{
					this.$Notice.error({
						title: '获取机构失败',
						desc:response.msg
					});
				}
			}
		},
		f_selectChange(selectarr){
			this.f_select_op=selectarr;
		},
		confirmF(){
			if(this.f_select_op.length>0){
				if(this.f_select_op[0].canChoose=='true'){
					this.mgInfo.instUuid=this.f_select_op[0].value;
					this.mgInfo.inst_name=this.f_select_op[0].title;
				}else{
					this.$Notice.error({
						desc:'请选择有效节点'
					});
					this.ft_load=false;
					let that=this;
					setTimeout(() => {
						that.ft_load=true;
					}, 200);
					return false
				}
				
			}else{
				this.mgInfo.instUuid='';
				this.mgInfo.inst_name='';
			}
			this.f_tree=false;
		},
		gotoChangePower(obj){
			this.mobileIsTrue=true;
			this.modalTitle='修改子管理员权限';
			this.saveUuid=obj.uuid;
			this.checkAllGroup=obj.roleUuids.split(',')
			this.mgInfo={
				mobile:obj.mobile,
				name:obj.name,
				inst_name:obj.inst_name,
				authority:obj.authoritydata,
				roleManager:obj.roleUuids,
				location:[],
				instUuid:obj.inst_uuid,
				deptUuid:'',
				password:'',
				repassword:''
			};
			this.modal_mg=true;
		},
		async save(){
			let form=JSON.parse(JSON.stringify(this.mgInfo));
			form.roleManager=this.checkAllGroup.join(',');
			if(this.modalTitle=="修改子管理员权限"){
					form.uuid=this.saveUuid;
			}
			let res=await saveSubAdmins(form);
			let response=res.data;
			if(response.code===200){
				this.$Notice.success({
					desc:'已保存'
				});
				this.modal_mg=false;
				this.pageNumber=1;
				this.getTable();
			}else{
				this.$Notice.error({
					title: '请求出错',
					desc:response.msg
				});
			}
			this.saveLoad=false;
			let that=this;
			setTimeout(()=>{
				that.saveLoad=true;
			},500)
		},
		async validate(){
			const reg=/^[\u4e00-\u9fa5]{2,5}$/;
			const preg=this.$store.state.app.pwdReg;
			let that=this;
			if(this.isRegister){
				if(this.mgInfo.authority.length<=0){
				this.$Notice.error({
					desc:'请选择子管理员的权限范围'
				});
				}else if(this.checkAllGroup.length<=0){
				this.$Notice.error({
					desc:'请选择子管理员的管理权限'
				});
				}else{
				this.save();
				}
			}else if(!reg.test(this.mgInfo.name)){
				this.$Notice.error({
				desc:'请输入真实姓名'
				});
			}else if(!this.mgInfo.location[0]){
				this.$Notice.error({
				desc:'请选择所在地'
				});
			}else if(this.mgInfo.instUuid.length<=0){
				this.$Notice.error({
				desc:'请选择所在机构'
				});
			}else if(!this.mgInfo.password){
				this.$Notice.error({
				desc:'请输入密码'
				})
			}else if(!preg.test(this.mgInfo.password)){
				this.$Notice.error({
				desc:'密码必须为8-20位，同时包含字母和数字'
				})
			}else if(!this.mgInfo.repassword){
				this.$Notice.error({
				desc:'请再次输入密码'
				})
			}else if(this.mgInfo.repassword!=this.mgInfo.password){
				this.$Notice.error({
				desc:'两次输入的密码不一致'
				})
			}else if(this.mgInfo.authority.length<=0){
				this.$Notice.error({
					desc:'请选择子管理员的权限范围'
				});
			}else if(this.checkAllGroup.length<=0){
				this.$Notice.error({
				desc:'请选择子管理员的管理权限'
				});
			}else{
				this.save();
			}
			that.saveLoad=false;
			setTimeout(() => {
				that.saveLoad=true;
			}, 500);
		},
		async mobile(){
		let res=await mobilepd(this.mgInfo.mobile);
		let response=res.data;
		if(response.code===200){
			if(response.data){
			this.isRegister=true;
			this.mgInfo.name=response.data.name;
			this.mgInfo.inst_name=response.data.inst_name;
			this.mgInfo.instUuid=response.data.inst_uuid;
			this.checkAll = false;
			this.checkAllGroup=[];
			}else{
			this.isRegister=false;
			let mobile=this.mgInfo.mobile;
			this.mgInfo={
				mobile:mobile,
				name:'',
				inst_name:'',
				authority:'',
				roleManager:'',
				location:[],
				instUuid:'',
				deptUuid:'',
				password:'',
				repassword:''
			}
			//this.getInst(this.userUuid);
			this.getFormInstTree(this.userUuid);
			this.checkAllGroup=[];
			}
			this.mobileIsTrue=true;
		}else{
			this.$Notice.error({
			desc:response.msg
			});
		}
    },
    async instChange(val){
      if(val.length>0){
        let res=await getDeptList(val);
        let response=res.data;
        if(response.code===200){
          this.partList=response.data;
        }else{
          this.$Notice.error({
            desc:response.msg
          });
        }
      }else{
        this.partList=[];
      }
      
    },
    async mobileChange(event){
      if(this.mgInfo.mobile.length=='11'){
        const reg=this.$store.state.app.mobileReg;
        if(reg.test(this.mgInfo.mobile)){
          await this.mobile();
          
        }else{
          this.$Notice.error({
            desc:'手机号格式错误'
          })
        }
      }else{
        this.mobileIsTrue=false;
      }
    },
    async delete(uuid){
      let res=await deleteSubadmins(uuid);
      let response=res.data;
      if(response.code===200){
        this.$Notice.success({
          desc:'已删除'
        });
        this.modal_role=false;
        this.pageNumber=1;
        this.getTable();
      }else{
        this.$Notice.error({
          desc:response.msg
        });
      }
    },
    async getTable(){
      this.loading=true;
      let res=await getSubAdminsTable(this.pageSize,this.pageNumber);
      let response=res.data;
      if(response.code===200){
        this.total=response.data.total;
        this.data=response.data.rows.map(item=>{
          if(!!item.created){
            item.time=item.created.slice(0,16)
          }else{
            item.time='';
          }
          return item
        });
      }else{
        this.$Notice.error({
          desc:response.msg
        });
      }
       this.loading=false;
    },
    pageSizeChange(size){
      this.pageNumber=1;
      this.pageSize=size;
      this.getTable();
    },
    pageChange(number){
        this.pageNumber=number;
        this.getTable();
    },
    handleAdd(){
      this.modal_mg=true;
      this.modalTitle='新增子管理员';
    },
    handleCheckAll () {
      if (this.indeterminate) {
          this.checkAll = false;
      } else {
          this.checkAll = !this.checkAll;
      }
      this.indeterminate = false;

      if (this.checkAll) {
          this.checkAllGroup = [
            '8148d7c810964be998d68ddb10e615f5',
            '94fe763a7072479cb5714b49f774c67c',
            '3d171d56f0a1410c8b41a61dd45755c0',
            '7c3d83aff33c4bbeb36ab44cbb084ffe'];
      } else {
          this.checkAllGroup = [];
      }
    },
    checkAllGroupChange (data) {
        if (data.length === 4) {
            this.indeterminate = false;
            this.checkAll = true;
        } else if (data.length > 0) {
            this.indeterminate = true;
            this.checkAll = false;
        } else {
            this.indeterminate = false;
            this.checkAll = false;
        }
    }
  },
  watch:{
    modal_mg:function(){
      if(!this.modal_mg){
		  this.f_select_op=[];
        this.checkAllGroup=[];
        this.checkAll=false;
        this.mobileIsTrue=false;
        this.mgInfo={
          mobile:'',
          name:'',
          inst_name:'',
          authority:'',
          roleManager:'',
          location:[],
          instUuid:'',
          deptUuid:'',
          password:'',
          repassword:''
        }
      }
    }
  },
  created(){
    let that=this;
    this.getTable();
    util.isCustomer(this);
    this.btnp=util.bpower(this,this.btn);
    // setTimeout(()=>{
    //     that.areasData=that.$store.state.user.areaData;
    //   },5000);
  }
}

</script>
<style lang='scss' >
</style>